var username = document.querySelector("[name = 'username']");
var password = document.querySelector("[name = 'password']");
var remember = document.querySelector("[name = 'remember']");
var form = document.querySelector("form");
var p = document.createElement("p");
p.className = "error";
username.onfocus = function () {
    if (this.nextElementSibling) { // 如果存在错误信息的p,就删除
        this.parentElement.removeChild(this.nextElementSibling);
    }
}
password.onfocus = function () {
    if (this.nextElementSibling) { // 如果存在错误信息的p,就删除
        this.parentElement.removeChild(this.nextElementSibling);
    }
}
if(getCookie("remusername")) {
    username.value = getCookie("remusername");
}
form.onsubmit = function (e) {
    // 取消默认事件
    var e = e || window.event;
    if (window.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
    if (username.value == "") {
        p.innerHTML = "用户名不能为空";
        username.parentElement.appendChild(p);
        return false;
    }
    var nameReg = /^[a-zA-Z]\w{5,15}$/;
    if (!nameReg.test(username.value)) {
        p.innerHTML = "用户名必须字母开头，由字母数字组成，6-16位";
        username.parentElement.appendChild(p);
        return false;
    }
    if (password.value == "") {
        p.innerHTML = "密码不能为空";
        password.parentElement.appendChild(p);
        return false;
    }
    var psdReg = /^\w{6,16}$/;
    if (!psdReg.test(password.value)) {
        p.innerHTML = "密码有数字字母组成，6-16位";
        password.parentElement.appendChild(p);
        return false;
    }


    // 发送注册请求
    pAjax({
        url:"./serve/login.php",
        data:{
            username: username.value,
            password: password.value
        },
        method: "post"
    }).then(res => {
        // console.log(res);
        var {meta: {status,msg}} = res;
        if(status == 201) {
            setCookie("username",username.value,7200);
            if(remember.checked) {
                setCookie("remusername",username.value,3600*24*7);
            }
            alert(msg)
            location.href = "shoe.html";
        }else{
            alert(msg);
            return false;
        }
    })
}